//
//  MVVMModelItem.m
//  semple-code-oc
//
//  Created by zhaoguoteng on 2022/1/4.
//

#import "MVVMModelItem.h"

@implementation MVVMModelItem

- (CGFloat)rowHeight {
    return 0;
}

- (NSString *)getTargetCellName {
    return nil;
}

- (NSString *)reusableIdentifier {
    NSString *clsName = NSStringFromClass(self.class);
    NSAssert([clsName containsString:@"Model"], @"命名不符合规范，后缀应该是Model");
    
    NSAssert(self.getTargetCellName.length > 0, @"getTargetCellName方法不能返回空串 or nil");
    
    NSString *cellName = [clsName stringByReplacingOccurrencesOfString:@"Model" withString:@"Cell"];
    NSAssert([cellName isEqualToString:self.getTargetCellName], @"getTargetCellName 方法返回的名字不符合规则，应为%@", cellName);
    
    return cellName;
}

- (MVVMItemCell *)mappingCellInTableView:(UITableView *)tableView {
    MVVMItemCell *cell = [self getCellInTableView:tableView];
    cell.baseItem = self;
    return cell;
}

- (CGFloat)rowHeightInTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
    
    if (self.rowHeight > 0) {
        return self.rowHeight;
    }
    
    if (self.rowCalculateHeight > 0) {
        return self.rowCalculateHeight;
    }
    
    MVVMItemCell *cell = [self getCellInTableView:tableView];
    cell.baseItem = self;
    self.rowCalculateHeight = [cell cellHeight];
    
    return self.rowCalculateHeight;
}

- (void)didSelectedCellInTableView:(UITableView *)tableView {
    
}

- (void)clearHeight {
    self.rowCalculateHeight = 0;
}

#pragma mark - private

- (MVVMItemCell *)getCellInTableView:(UITableView *)tableView {
    MVVMItemCell *cell = [tableView dequeueReusableCellWithIdentifier:self.conformReusableIdentifier];
    if (!cell) {
        [tableView registerClass:NSClassFromString(self.conformReusableIdentifier)
          forCellReuseIdentifier:self.conformReusableIdentifier];
        cell = [self getCellInTableView:tableView];
    }
    return cell;
}

- (NSString *)conformReusableIdentifier {
    Class cls = NSClassFromString(self.reusableIdentifier);
    NSAssert(cls, @"缺少%@类", cls);
    if (cls == nil) {
        // 占位cell
        return NSStringFromClass(MVVMItemCell.class);
    }
    return self.reusableIdentifier;
}

@end
